//
//  InformationTableViewController.m
//  CarHome
//
//  Created by lanou3g on 15-4-25.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "InformationTableViewController.h"
#import "CellContent.h"
#import "Focusimg.h"
#import "UIImageView+WebCache.h"
#import "InformationTableViewCell.h"
#import "NetWorkHandler.h"
#import "IndexdetailTableViewCell.h"
#import "SubInformationViewController.h"



@interface InformationTableViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>

@property (nonatomic, assign) BOOL isAutoMove;

- (void)loadPeriodicImageView;// 加载轮播图片
- (void)settupRefresh;// 添加刷新加载

@end

@implementation InformationTableViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.imgArray = [NSMutableArray array];
    self.allCellContentDataArray = [NSMutableArray array];
    self.allFocusimgDataArray = [NSMutableArray array];

    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"资讯";
    
    
    [self.tableView registerNib:[UINib nibWithNibName:@"InformationTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"IndexdetailTableViewCell" bundle:nil] forCellReuseIdentifier:@"indexdetail"];
    
    [self settupRefresh];
    
    
}




- (void)settupRefresh
{
    // 下拉刷新
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    [self.tableView.header beginRefreshing];
    // 上拉加载
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
  
}

- (void)loadMoreData
{
    __block typeof(self) weakSelf = self;
    NSInteger count = _allCellContentDataArray.count;
    NSString *lasttime = [_allCellContentDataArray[count - 1] lasttime];
    NSArray *array = [_urlIString componentsSeparatedByString:@"-p1"];
    NSString *str = [NSString stringWithFormat:@"-p2-s30-l%@.json", lasttime];
    NSString *urlStr = [array[0] stringByAppendingString:str];
    [NetWorkHandler getConnectionWithURL:urlStr completion:^(id result) {
            for (NSDictionary *dict in result[@"result"][@"newslist"]) {
            CellContent *c = [[CellContent new]autorelease];
            [c setValuesForKeysWithDictionary:dict];
            [weakSelf.allCellContentDataArray addObject:c];
            [self.tableView reloadData];
            }

    }];
    if ([_allCellContentDataArray[count - 1] lasttime] != nil) {
        [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    } else{
        NSLog(@"加载完了");
    }
    
}


-(void)loadPeriodicImageView
{
    
    self.v = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, UISCREENWIDTH, (160.0 / UISCREENHEIGHT) * UISCREENHEIGHT)] autorelease];
    _v.backgroundColor = [UIColor blackColor];
    self.tableView.tableHeaderView  = _v;
    //[self.view addSubview:v];
    self.scrollView = [[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, UISCREENWIDTH, (160.0 / UISCREENHEIGHT) * UISCREENHEIGHT)]autorelease];
    [_v addSubview:_scrollView];
    
    for (int i = 0 ; i < 6; i++) {
        UIImageView *imageV = [[[UIImageView alloc] initWithImage:_imgArray[i]]autorelease];
        //NSLog(@"%d%@", i , _imgArray[i]);
        imageV.frame = CGRectMake(UISCREENWIDTH * (i + 1), 0, UISCREENWIDTH, (160.0 / UISCREENHEIGHT) * UISCREENHEIGHT);
        imageV.tag = i + 1;
        [_scrollView addSubview:imageV];
        
    }
    UIImageView *headImageView = [[[UIImageView alloc] initWithImage:_imgArray[5]]autorelease];
    headImageView.frame = CGRectMake(0, 0, UISCREENWIDTH, (160.0 / UISCREENHEIGHT) * UISCREENHEIGHT);
    [_scrollView addSubview:headImageView];
    //NSLog(@"%@", _imgArray[5]);
    UIImageView *footImageView = [[[UIImageView alloc] initWithImage:_imgArray[0]]autorelease];
    //NSLog(@"%@", _imgArray[0]);
    footImageView.frame = CGRectMake(UISCREENWIDTH * 7, 0, UISCREENWIDTH, (160.0 / UISCREENHEIGHT) * UISCREENHEIGHT);
    [_scrollView addSubview:footImageView];
    // NSLog(@"%@",_imgArray);
    _scrollView.contentSize = CGSizeMake(_scrollView.frame.size.width * 8, 0);
    _scrollView.bounces = NO;
    _scrollView.alwaysBounceHorizontal = NO;
    _scrollView.alwaysBounceVertical = NO;
    //_scrollView.contentInset = UIEdgeInsetsMake(0, 10, 0, 0);
    _scrollView.pagingEnabled = YES;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.delegate = self;
    _scrollView.contentOffset = CGPointMake(UISCREENWIDTH, 0);
    self.pageControl = [[[UIPageControl alloc] initWithFrame:CGRectMake(0, _scrollView.frame.size.height - (30 / UISCREENHEIGHT) * UISCREENHEIGHT, _scrollView.frame.size.width, 20 / UISCREENHEIGHT * UISCREENHEIGHT)] autorelease];
    [_pageControl addTarget:self action:@selector(pageControlAction:) forControlEvents
                           :UIControlEventEditingChanged];
     _pageControl.numberOfPages = 6;
    _pageControl.currentPage = 0;
    _pageControl.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.5];
    _pageControl.enabled = NO;
    [_v addSubview:_pageControl];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(autoMoveImageView) userInfo:self repeats:YES];
    
}

- (void)autoMoveImageView
{
    if (_pageControl.currentPage == 5 ){
        _pageControl.currentPage = 0;
        [self pageControlAction:_pageControl];
        return;
    }
    if (_pageControl.currentPage < 6) {
        _pageControl.currentPage ++;
    }
    [self pageControlAction:_pageControl];
    
}

- (void)pageControlAction:(UIPageControl *)sender
{
    CGPoint offset = CGPointMake((sender.currentPage + 1) * UISCREENWIDTH, 0);
    [_scrollView setContentOffset:offset animated:YES];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView// 自动回弹结束时
{
    if (_scrollView.contentOffset.x > self.view.frame.size.width * 6) {
        [_scrollView setContentOffset:CGPointMake(UISCREENWIDTH, 0)];
        _pageControl.currentPage = 0;
        return;
    }
    if (_scrollView.contentOffset.x <= 0 ) {
        [_scrollView setContentOffset:CGPointMake(UISCREENWIDTH * 6, 0)];
        _pageControl.currentPage = 5;
        return;
    }
    _pageControl.currentPage = scrollView.contentOffset.x/ scrollView.frame.size.width - 1;
}




-(void)loadData
{
    __block InformationTableViewController *weakSelf = self;
    [NetWorkHandler getConnectionWithURL:_urlIString completion:^(id result) {
        for (NSDictionary *dict in result[@"result"][@"newslist"]) {
            CellContent *c = [[CellContent new] autorelease];
            [c setValuesForKeysWithDictionary:dict];
            
            NSArray *a = [_urlIString componentsSeparatedByString:@"-c"];
            a = [a[1] componentsSeparatedByString:@"-nt"];
            if ( ![a[0] isEqualToString:@"0"] && _allCellContentDataArray.count == 20 ){
                [_allCellContentDataArray removeAllObjects];
            }
            [weakSelf.allCellContentDataArray  addObject:c];
            // 刷新表格
            [self.tableView reloadData];
            
        }
        for (NSDictionary *dict in result[@"result"][@"focusimg"]) {
            Focusimg *f = [[Focusimg new] autorelease];
            [f setValuesForKeysWithDictionary:dict];
            [weakSelf.allFocusimgDataArray addObject:f];
            if (f.imgData == nil) {
                [f  addObserver:self forKeyPath:@"imgData" options:NSKeyValueObservingOptionNew context:nil];
            } else {
                [weakSelf.imgArray addObject:f.imgData];
            }
            [self.tableView reloadData];
        }
        [self.tableView.header endRefreshing];
        
    }];
    
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
      return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _allCellContentDataArray.count ;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CellContent *c = _allCellContentDataArray[indexPath.row];
    NSArray *a = [_urlIString componentsSeparatedByString:@"-c"];
    a = [a[1] componentsSeparatedByString:@"-nt"];
    // 通过图片字符串有没有内容来判断用哪个cell模型
    if (c.smallpic.length == 0) {
        IndexdetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"indexdetail"];
        NSString *str = c.indexdetail;
        NSArray *array0 = [str componentsSeparatedByString:@"㊣"];
        NSArray *array1 = [array0[2] componentsSeparatedByString:@","];
        [cell.imageView1 sd_setImageWithURL:[NSURL URLWithString:array1[0]]];
        [cell.imageView2 sd_setImageWithURL:[NSURL URLWithString:array1[1]]];
        [cell.imageView3 sd_setImageWithURL:[NSURL URLWithString:array1[2]]];
        cell.titleLabel.text = c.title;
        cell.timeLabel.text = c.time;
        cell.replycountLabel.text = [NSString stringWithFormat:@"%@图片", c.replycount];
        return cell;
    }
    InformationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.titleLabel.text = c.title;
    cell.timeLabel.text = c.time;
    cell.replycountLabel.text = [NSString stringWithFormat:@"%@评论", c.replycount];//重点，这个地方是把，NSNumber的类型数据，给字符串
    //通过判断网址中的c的后缀的不同，来确定是不是行情页面
    if ( ![a[0] isEqualToString:@"0"] ) {
        NSString *str = c.smallpic;// 准备要改的图片网址
        str = [str stringByReplacingCharactersInRange:NSMakeRange(7, 3) withString:@"car0"];
        [cell.imageViewName sd_setImageWithURL:[NSURL URLWithString:str]];
        cell.replycountLabel.text = nil;
        return cell;
    }
    if (c.imageData == nil) {
       
        NSIndexPath *path = [indexPath retain];
        [c addObserver:self forKeyPath:@"imageData" options:NSKeyValueObservingOptionNew context:path];
    } else {
        cell.imageViewName.image = c.imageData;
    }
    return cell;
        
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    
    if ([keyPath isEqualToString:@"imageData"]) {

        InformationTableViewCell *cell =  (InformationTableViewCell *)[self.tableView cellForRowAtIndexPath:context];
        UIImage *newImage = change[@"new"];
        //NSLog(@"!!!!!!!!!!%@", change[@"new"]);
        //NSLog(@"我不是空的%@",newImage);// 用来判断行情的图片是否为空（因为行情页面的图片弄不出来）
        if (change[@"new"]!= [NSNull null]) {
            cell.imageViewName.image = newImage;
        }
        [self.tableView reloadRowsAtIndexPaths:@[(NSIndexPath *)context] withRowAnimation:UITableViewRowAnimationAutomatic];
        [object removeObserver:self forKeyPath:keyPath context:context];
      
    }  else {
        UIImage *image = change[@"new"];
        [self.imgArray addObject:image];
        [object removeObserver:self forKeyPath:keyPath context:context];
        if (self.imgArray.count == 6) {
          
            [self loadPeriodicImageView];
        }
        [self.tableView reloadData];
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CellContent *c = _allCellContentDataArray[indexPath.row];
    if (c.smallpic.length == 0 ) {
        return 150;
    }
    return 100;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CellContent *c = _allCellContentDataArray[indexPath. row];
    SubInformationViewController *subVC = [SubInformationViewController new];
    subVC.Id = c.Id;
    [self.navigationController pushViewController:subVC animated:YES];
    
}



-(void)dealloc
{
//    [_allCellContentDataArray release];
//    [_allFocusimgDataArray release];
//    
    
    
    
    [super dealloc];
}



@end
